package com.seven.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;

import java.util.*;

/**
 * @author longlong
 * @date 2024/2/22 9:40
 * description
 */

public class JWTUtil {
    public static String sign = "longlong";

    //1.生成token
    public static String generateToken(String username, List<String> roles){
        Map<String,Object> header=new HashMap<String,Object>();
        header.put("alg","HS256");
        header.put("typ","JWT");
        Calendar calendar=Calendar.getInstance();//获取当前时间
        calendar.set(Calendar.HOUR,24); //在当前时间的基础上增加1800秒
        Date expire = calendar.getTime(); //追加1800后获取时间。
        String token = JWT.create().withHeader(header)
                .withIssuedAt(new Date()) //设置token颁发时间
                .withExpiresAt(expire) //设置token失效时间
                .withClaim("username", username) //设置自己的字段--唯一标识
                .withClaim("roles",roles) //设置当前用户的权限码
                .sign(Algorithm.HMAC256(sign));
        return token;
    }
    //2.验证token
    public static boolean verifyToken(String token){

        try {
            JWT.require(Algorithm.HMAC256(sign)).build().verify(token);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    //3.解析token
    public static String parseToken(String token){
        String username = JWT.decode(token).getClaim("username").asString();
        return username;
    }
    //4.解析角色
    public static List<String> parseRoles(String token){
        List<String> roles = JWT.decode(token).getClaim("roles").asList(String.class);
        return roles;
    }

    public static void main(String[] args) {
        String token = generateToken("lisi",new ArrayList<>());
        System.out.println(token);
        System.out.println(parseToken(token));
        System.out.println(verifyToken(token));
    }
}

